export default class BluetoothManager {
    constructor() {
        this.deviceInstances = new Map();
        this.receiveCallbacks = new Map();
        this.breakCallbacks = new Map();
    }

    async initBle(index, serviceUuid, txCharUuid, rxCharUuid, deviceName) {
        try {
            if (!navigator.bluetooth) throw new Error("浏览器不支持蓝牙");
            if (!await navigator.bluetooth.getAvailability()) throw new Error("蓝牙不可用");

            const device = await navigator.bluetooth.requestDevice({
                filters: [{ namePrefix: deviceName }],
                // filters: [{ name: deviceName }],
                optionalServices: [serviceUuid]
            });
            console.log(1)
            const server = await device.gatt.connect();
            console.log(2)

            const service = await server.getPrimaryService(serviceUuid);
            console.log(3)

            const txChar = await service.getCharacteristic(txCharUuid);
            console.log(4)

            const rxChar = await service.getCharacteristic(rxCharUuid);
            console.log(5)

            this.deviceInstances.set(index, { device, txChar, rxChar });
            if (rxChar.properties.notify) {
                await rxChar.startNotifications();
                rxChar.addEventListener('characteristicvaluechanged', (event) => {
                    if (this.receiveCallbacks.has(index)) {
                        this.receiveCallbacks.get(index)(event.target.value, index);
                    }
                });
            }

            device.addEventListener('gattserverdisconnected', () => {
                if (this.breakCallbacks.has(index)) {
                    this.breakCallbacks.get(index)();
                }
                this.deviceInstances.delete(index);
            });

            return true;
        } catch (error) {
            console.error(`设备 ${index + 1} 连接失败:`, error);
            return false;
        }
    }

    async sendData(index, data) {
        const instance = this.deviceInstances.get(index);
        if (!instance) return console.error(`设备 ${index + 1} 未连接`);
        await instance.txChar.writeValue(Buffer.from(data));
    }

    setCallbacks(index, receiveFun, breakFun) {
        this.receiveCallbacks.set(index, receiveFun);
        this.breakCallbacks.set(index, breakFun);
    }

    async disconnect(index) {
        const instance = this.deviceInstances.get(index);
        if (instance) {
            await instance.device.gatt.disconnect();
            this.deviceInstances.delete(index);
        }
    }
}